package org.prx.prp.view; 


import java.util.Random;

import org.prx.prp.BackgroundDataService;
import org.prx.prp.IBackgroundDataService;
import org.prx.prp.controller.SchedulingManager;
import org.prx.prp.controller.SyncManager;
import org.prx.prp.utility.DatabaseAdapter;
import org.prx.prp.utility.DatabaseHelper;
import org.prx.prp.view.LiveViewActivity;
import org.prx.prp.R;
import android.app.ActivityGroup; 
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent; 
import android.content.ServiceConnection;
import android.os.Bundle; 
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Window;
import android.os.AsyncTask;

public class SplashActivity extends ActivityGroup { 
      
     private final int SPLASH_DISPLAY_LENGTH = 000; 
     private Handler mHandler;
     private DatabaseHelper mDatabaseHelper;
     private ProgressDialog mDialog;
     private int mDialogProgress = 0;
     private String mDialogMessage = "Starting up...";
     private Boolean syncCompleted = false;
     private AsyncTask<Context, Integer, Boolean> mTask;
     private boolean mIsBound = false;
     private boolean keepGoing = true;
     private Handler iHandler;
     
     private IBackgroundDataService mDataService = null;
     
     private ServiceConnection mConnection = new ServiceConnection() {
    	 public void onServiceConnected(ComponentName className, IBinder service){
    		 mDataService = IBackgroundDataService.Stub.asInterface(service);
    		 try {
    			 mDataService.startSync();
    		 } catch(RemoteException e){
    			 e.printStackTrace();
    		 }
    	 }
    	 
    	 public void onServiceDisconnected(ComponentName className){
    		 Log.d("PRPAND", "SOMETHING WENT VERY WRONG");
    	 }
     };

     @Override 
     public void onCreate(Bundle mBundle) { 
          super.onCreate(mBundle); 
          requestWindowFeature(Window.FEATURE_NO_TITLE);
          setContentView(R.layout.splash);
          
          class DataSyncTask extends AsyncTask<Context, Integer, Boolean> {
        	  @Override
        	  protected Boolean doInBackground(Context... c){
        		  (new DatabaseHelper(c[0], "org.prx")).initialize();
        		  publishProgress(1);
        		  DatabaseAdapter.initDatabaseAdapter(c[0]);
        		  publishProgress(2);
        		  SchedulingManager.getInstance();
        		  publishProgress(3);
        		  return true;
        	  }
        	  
        	  @Override
        	  protected void onProgressUpdate(Integer... i) {
        		  switch(i[0]){
        		  
        		  case 1:
        			  mDialogMessage ="Initializing Database";
        			  mDialogProgress = 8;
        			  break;
        			  
        		  case 2:
        			  mDialogMessage = "Syncing Schedules";
        			  mDialogProgress = 21;
        			  break;
        		  case 3:
        			  mDialogMessage = "Done!";
        			  mDialogProgress = 99;
        			  keepGoing = false;
        		  }
        		  
        		  mDialog.setMessage(mDialogMessage);
        		  mDialog.setProgress(mDialogProgress);
        	  }
        	  
        	  @Override
        	  protected void onPostExecute(Boolean b){
        		  syncCompleted = b;
        		  mDialog.dismiss();
        		  SplashActivity.this.startActivity(new Intent(SplashActivity.this, LiveViewActivity.class));
        	  }
          }
          
          
          
          bindService(new Intent(this, BackgroundDataService.class), mConnection, BIND_AUTO_CREATE);
          //if mConnection.startService(new Intent(this, BackgroundDataService.class));
         
          Handler fHandler = new Handler();
          fHandler.postDelayed(new Runnable(){
        	  public void run(){
        		  if (mIsBound){
        			  try {
        				  mDataService.startSync();
        			  } catch (RemoteException e) {
        				  e.printStackTrace();
        			  }
        		  }
        	  }
          }, 3000);
          
          mDatabaseHelper = new DatabaseHelper(this, "org.prx");
          mDatabaseHelper.initialize();
        
          
          mHandler = new Handler();
          iHandler = new Handler();
          mDialog = new ProgressDialog(this);
          mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   	   	  mDialog.setCancelable(false);
          
          mHandler.post(new Runnable(){  
               public void run() { 
            	   if (!syncCompleted){
            		   	mDialog.show();
            		    mDialog.setProgress(mDialogProgress);
            		    mDialog.setMessage(mDialogMessage);
            	          
            	        mTask = new DataSyncTask();
            	        mTask.execute(SplashActivity.this);
            	   } else {
            		   mHandler.postDelayed(new Runnable(){
            			   public void run() {
            				   SplashActivity.this.startActivity(new Intent(SplashActivity.this, LiveViewActivity.class));
            			   }
            		   }, 3000);
            	   }
               } 
          });
          
          final Random r = new Random();
          
          Runnable increaseCounter = new Runnable(){
        	  public void run(){
        		  mDialogProgress++;
        		  mDialog.setProgress(mDialogProgress);
        		  if(keepGoing && mDialogProgress < 92)
        			  iHandler.postDelayed(this, r.nextInt(400) + (mDialogProgress * 9));
        	  }
          };
          
          iHandler.postDelayed(increaseCounter, 750);
     } 
     
     @Override
     public void onDestroy(){
    	 if (mConnection != null) {
    		 unbindService(mConnection);
    	 }
    	 
    	 super.onDestroy();
     }
     
     
     // We don't want the splash screen to show up when the user presses "back"
     @Override
     public void startActivity(Intent intent){
    	 super.startActivity(intent);
    	 finish();
     }
}